package com.aaa.springboot_rbac.util;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @FileName: LoginFilter
 * @Description:
 * @Author: 张钰哲
 * @CreateTime: 2025/9/1 20:07
 * @Version: 1.0.0*/


@Component
@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制转换
        HttpServletRequest request =  (HttpServletRequest)servletRequest;
        HttpServletResponse response =  (HttpServletResponse)servletResponse;
        //获取请求uri
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/html/login.html")||requestURI.contains("/user/login")||requestURI.endsWith(".css")||requestURI.endsWith(".js")||requestURI.contains("/swagger-ui/index.html")){
            filterChain.doFilter(request,response);
        }else  {
            //获取session用户信息
            Object user = request.getSession().getAttribute("user");
            if (user==null){
                //判断为空，说明没有登录
                //重定向
                response.sendRedirect(request.getContextPath()+"/html/login.html");
            }else  {
                filterChain.doFilter(request,response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
